<template>
    <div class="main-container">
          
        <el-card class="box-card !border-none" shadow="never">
            <el-alert type="warning" :closable="false" class="!mb-[20px]">
                <template #default>
                    <p class="mb-[5px]">结算周期：根据计划任务执行，默认一天结算一次</p>
                    <p class="mb-[5px]">在奖励规则时间段内，奖项只会在首次达到条件后发放，不会重复发放</p>
                 </template>
            </el-alert>
            <div class="flex justify-between items-center">
                <span class="text-page-title">{{ pageName }}</span>
                <el-button type="primary" @click="addEvent">
                    {{ t('添加奖励规则') }}
                </el-button>
            </div>

            <el-card class="box-card !border-none my-[10px] table-search-wrap" shadow="never">
                <el-form :inline="true" :model="rewardRuleTable.searchParam" ref="searchFormRef">
                    <el-form-item :label="t('奖励规则类型')" prop="type">
                        <el-select v-model="rewardRuleTable.searchParam.type" :placeholder="t('请选择奖励规则类型')" clearable>
                            <el-option :label="t('发布内容')" :value="1" />
                            <el-option :label="t('点赞')" :value="2" />
                            <el-option :label="t('评论')" :value="3" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="loadrewardRuleList()">{{ t('search') }}</el-button>
                        <el-button @click="resetForm(searchFormRef)">{{ t('reset') }}</el-button>
                    </el-form-item>
                </el-form>
            </el-card>  
            <div class="mb-[10px] flex items-center">
                    <el-checkbox v-model="toggleCheckbox" size="large" class="px-[14px]" @change="toggleChange" :indeterminate="isIndeterminate" />
                    <el-button @click="batchDeleteEvent" size="small" >{{t("批量删除")}}</el-button>
            </div>
            <div class="mt-[10px]">
                <el-table :data="rewardRuleTable.data" size="large" ref="rewardRuleTableRef" v-loading="rewardRuleTable.loading" @selection-change="handleSelectionChange">
                    <template #empty>
                        <span>{{ !rewardRuleTable.loading ? t('emptyData') : '' }}</span>
                    </template>
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="type" :label="t('奖励规则类型')" min-width="120" >
                        <template #default="{ row }">
                            {{ row.type == 1 ? t('发布内容') : row.type == 2 ? t('点赞') : t('评论') }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="num" :label="t('奖励规则数量')" min-width="120" />
                    <el-table-column :label="t('奖励规则时间')"  min-width="150">
                        <template #default="{ row }">
                            <div>
                                <p>开始：{{ formatDateTime(row.start_time) }}</p>
                                <p>结束：{{ formatDateTime(row.end_time) }}</p>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="giftPackInfo" :label="t('奖励规则内容')" min-width="130">
                        <template #default="{ row }">
                            <div>
                                <p v-if="row.rule_json?.point?.value>0">{{ t('积分') }}：{{ row.rule_json?.point?.value }}</p>
                                <p v-if="row.rule_json?.balance?.value>0">{{ t('余额') }}：{{ row.rule_json?.balance?.value }}</p>
                                <template v-if="row.rule_content">
                                    <p v-for="(item,index) in row.rule_content" :key="index">{{ item.info }}</p>
                                </template>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" :label="t('status')" min-width="120" >
                        <template #default="{ row }">
                            <el-tag :type="row.status == 1 ? 'success' : 'danger'" @click="changeStatus(row)">{{ row.status == 1 ? t('开启') : t('关闭')}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="create_time" :label="t('createTime')" min-width="120" />
                    <el-table-column :label="t('operation')" fixed="right" align="right" min-width="120">
                        <template #default="{ row }">
                            <el-button type="primary" link @click="editEvent(row)">{{ t('edit') }}</el-button>
                            <el-button type="primary" link @click="details(row)">{{ t('发放记录') }}</el-button>
                            <el-button type="primary" link @click="deleteEvent(row)">{{ t('删除') }}</el-button>
                        </template>
                    </el-table-column>

                </el-table>
                <div class="mt-[16px] flex justify-end">
                    <el-pagination v-model:current-page="rewardRuleTable.page" v-model:page-size="rewardRuleTable.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="rewardRuleTable.total"
                        @size-change="loadrewardRuleList()" @current-change="loadrewardRuleList" />
                </div>
            </div>
        </el-card>

        <reward-rule-detail ref="rewardRuleDetailRef"  />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { t } from '@/lang'
import { getRewardRuleList,modifyRewardRuleStatus,deleteRewardRule} from '@/addon/sow_community/api/reward_rule'
import { img, setTablePageStorage, getTablePageStorage } from '@/utils/common'
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { cloneDeep } from 'lodash-es'
import RewardRuleDetail from './components/reward_rule-detail.vue'

const route = useRoute()
const router = useRouter()
const pageName = route.meta.title
const repeat = ref(false)
const activeName = ref('')
const rewardRuleTable = reactive<any>({
    page: 1,
    limit: 10,
    total: 0,
    loading: true,
    data: [],
    searchParam: {
        type: '',
    }
})

const searchFormRef = ref<FormInstance>()

const formatDateTime = (timestamp: number) => {
    const date = new Date(timestamp * 1000); // 秒转毫秒
    const y = date.getFullYear();
    const m = ('0' + (date.getMonth() + 1)).slice(-2);
    const d = ('0' + date.getDate()).slice(-2);
    const h = ('0' + date.getHours()).slice(-2);
    const min = ('0' + date.getMinutes()).slice(-2);
    const s = ('0' + date.getSeconds()).slice(-2);
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
};

/**
 * 获取社区分类列表
 */
const loadrewardRuleList = (page: number = 1) => {
    rewardRuleTable.loading = true
    rewardRuleTable.page = page

    const searchData = cloneDeep(rewardRuleTable.searchParam)
    getRewardRuleList({
        page: rewardRuleTable.page,
        limit: rewardRuleTable.limit,
        ...rewardRuleTable.searchParam
    }).then((res: any) => {
        rewardRuleTable.loading = false
        rewardRuleTable.data = res.data.data
        rewardRuleTable.total = res.data.total
        setTablePageStorage(rewardRuleTable.page, rewardRuleTable.limit, searchData)
    }).catch(() => {
        rewardRuleTable.loading = false
    })
}
loadrewardRuleList(getTablePageStorage(rewardRuleTable.searchParam).page)

const addEvent = () => {
    router.push('/sow_community/reward_rule/add')
}

const editEvent = (data: any) => {
    router.push('/sow_community/reward_rule/edit?rule_id=' + data.rule_id)
}
const rewardRuleDetailRef = ref()
const details = (data: any) => {
    rewardRuleDetailRef.value.setFormData({id:data.rule_id})
    rewardRuleDetailRef.value.showDialog = true
}
const changeStatus = (data: any) => {
    console.log(data)
    modifyRewardRuleStatus({
        rule_id: data.rule_id,
        status: data.status == 1 ? 0 : 1
        // status: data.status
    }).then((res: any) => {
        loadrewardRuleList()
    }).catch(() => {
        loadrewardRuleList()
    })
}
const deleteEvent = (data: any) => {
    ElMessageBox.confirm(t('删除奖励规则同时会清空所有发放记录'), t('warning'),
        {
            confirmButtonText: t('confirm'),
            cancelButtonText: t('cancel'),
            type: 'warning'
        }
    ).then(() => {
        deleteRewardRule({
            ids: [data.rule_id]
        }).then(() => {
            loadrewardRuleList()
        }).catch(() => {
        })
    })
    // deleteRewardRule({
    //     ids: [data.rule_id]
    // }).then((res: any) => {
    //     loadrewardRuleList()
    // })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    loadrewardRuleList()
}

// 批量复选框
const toggleCheckbox = ref()
// 复选框中间状态
const isIndeterminate = ref(false)
// 监听批量复选框事件
const toggleChange = (value: any) => {
    isIndeterminate.value = false
    rewardRuleTableRef.value.toggleAllSelection()
}
const rewardRuleTableRef = ref()
// 选中数据
const multipleSelection: any = ref([])

// 监听表格单行选中
const handleSelectionChange = (val: []) => {
    multipleSelection.value = val

    toggleCheckbox.value = false
    if (multipleSelection.value.length > 0 && multipleSelection.value.length < rewardRuleTable.data.length) {
        isIndeterminate.value = true
    } else {
        isIndeterminate.value = false
    }

    if (multipleSelection.value.length == rewardRuleTable.data.length && rewardRuleTable.data.length && multipleSelection.value.length) {
        toggleCheckbox.value = true
    }
}
// 批量删除
const batchDeleteEvent = () => {
    if (multipleSelection.value.length == 0) {
        ElMessage({
            type: 'warning',
            message: `${t('请先选择需要批量操作的社区奖励规则')}`
        })
        return
    }

    ElMessageBox.confirm(t('确定要批量删除选中的社区奖励规则吗？'), t('warning'), {
        confirmButtonText: t('confirm'),
        cancelButtonText: t('cancel'),
        type: 'warning'
    }).then(() => {
        const comment_ids: any = []
        multipleSelection.value.forEach((item: any) => {
            comment_ids.push(item.rule_id)
        })

        deleteRewardRule({
            ids: comment_ids
        }).then(() => {
            loadrewardRuleList()
        }).catch(() => {
        })
    })
}
</script>

<style lang="scss" scoped>
</style>
